<template>
    <div>
        <div>
            <span class="title text-6 mb-8 mr-4">购买车位</span>
            <span @click="router.back()" class="text-slate-400">返回</span>
        </div>
        <div class="my-8 w-full">
            <el-form :model="form" label-position="top" ref="formRef">
                <el-form-item label="停车场" required prop="parkId">
                    <el-select
                        v-model="form.parkId"
                        placeholder="请选择停车场"
                        clearable
                    >
                        <el-option
                            v-for="item in parkOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="停车位" required prop="parkSpaceId">
                    <el-select
                        v-model="form.parkSpaceId"
                        placeholder="请选择停车位"
                        clearable
                    >
                        <el-option
                            v-for="item in parkSpaceOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    class="w-full"
                    label="购买天数"
                    required
                    prop="packageId"
                >
                    <div class="w-full flex flex-wrap justify-between">
                        <div
                            class="b-2 b-solid rounded-2 p-4 mb-4 w-[30%]"
                            v-for="item in packageList"
                            :class="{
                                'b-blue b-2 bg-blue-50':
                                    form.packageId === item.id,
                                'b-slate-300': form.packageId !== item.id,
                            }"
                            @click="form.packageId = item.id"
                        >
                            <div class="flex flex-col mb-4">
                                <div class="mr-2 line-height-4">
                                    {{ item.name }}
                                </div>
                                <div class="mr-2">{{ item.day }} 天</div>
                            </div>
                            <div class="flex flex-col items-end">
                                <div
                                    class="text-slate-500 line-height-4"
                                    style="text-decoration: line-through"
                                >
                                    {{ item.price }}元
                                </div>
                                <div
                                    class="text-4"
                                    :class="{
                                        'text-blue-500':
                                            form.packageId === item.id,
                                    }"
                                >
                                    {{ item.realPrice }}元
                                </div>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="支付方式" required prop="payMethod">
                    <el-radio-group v-model="form.payMethod">
                        <el-radio
                            v-for="item in payMethodList"
                            :key="item.id"
                            :label="item.name"
                            border
                            >{{ item.name }}</el-radio
                        >
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div class="flex justify-center items-center mt-16">
                <el-button
                    type="success"
                    icon="Check"
                    size="large"
                    @click="formSubmit"
                    >支付</el-button
                >
            </div>
        </div>
        <PayModal ref="payRef" />
    </div>
</template>

<script setup lang="ts">
import { getOwnerByIdApi, getOwnerPageApi, updateOwnerApi } from '@/apis/owner'
import { getPackagePageApi } from '@/apis/package'
import { getParkOptionListApi } from '@/apis/park'
import { getParkSpacePageApi, updateParkSpaceApi } from '@/apis/parkSpace'
import { getPayMethodPageApi } from '@/apis/payMethod'
import PayModal from '@/components/PayModal.vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 用户信息
const user = ref<any>(JSON.parse(localStorage.getItem('user') || '{}'))

// 付款弹窗
const payRef = ref<any>(null)

const formRef = ref<any>(null)
// 添加表单数据
const defaultAddVal = {
    parkId: undefined, // 停车场id
    parkSpaceId: undefined, // 停车位id
    packageId: undefined, // 套餐id
    payMethod: undefined, // 支付方式id
}
const form = ref(cloneDeep(defaultAddVal))
// 添加提交
const formSubmit = () => {
    formRef.value!.validate(async (valid) => {
        if (valid) {
            // 付钱
            const pack = getPackageById(form.value.packageId)
            const res = await payRef.value.pay({
                amount: pack.price,
                realAmount: pack.realPrice,
                method: form.value.payMethod,
                type: 1,
                comment: `${user.value.id}-${user.value.name}购买停车位${form.value.parkId}-${form.value.parkSpaceId}`,
            })

            if (!res) return
            // 修改车主信息
            const ownerInfo = (await getOwnerByIdApi(user.value.id)) as any
            if (!ownerInfo) return
            const oldExpireTime: any = dayjs(ownerInfo.expireTime)
            let newExpireTime = oldExpireTime
            if (!oldExpireTime.isBefore(dayjs())) {
                newExpireTime = dayjs()
                    .add(pack.day, 'day')
                    .format('YYYY-MM-DD HH:mm:ss')
            } else {
                newExpireTime = oldExpireTime
                    .add(pack.day, 'day')
                    .format('YYYY-MM-DD HH:mm:ss')
            }

            const updateOwnerRes = await updateOwnerApi(user.value.id, {
                expireTime: newExpireTime,
                parkSpaceId: form.value.parkSpaceId,
            })
            ElMessage.success('购买成功')
            router.back()
        } else {
            return false
        }
    })
}

// 停车场下拉选项
const parkOptions = ref<any>([])

// 获取停车场下拉选项
const getParkOptions = async () => {
    const res = (await getParkOptionListApi()) as any
    parkOptions.value = res
}

// 停车位列表
const parkSpaceList = ref<any>([])
const parkSpaceOptions = ref<any>([])
const getParkSpaceList = async () => {
    // 查询出所有车位
    const res = (await getParkSpacePageApi({
        type: 1,
        limit: 1000,
    })) as any
    // 查询出所有车主
    const owners = (await getOwnerPageApi({
        limit: 1000,
    })) as any
    const currentUser = owners.rows.find(item => item.id === user.value.id)
    // 筛选出车位id存在的所有车主的车位id
    const ownerParkSpaceIds = owners.rows
        .filter((item) => item.parkSpaceId)
        .map((item) => item.parkSpaceId)
    //
    parkSpaceList.value = res.rows.filter(
        (item) => {
            if(currentUser.parkSpaceId === item.id) return true
            return !ownerParkSpaceIds.includes(item.id)
        }
    )
}

watch(
    () => form.value.parkId,
    (val) => {
        if (!val) {
            parkSpaceOptions.value = []
            return
        }
        const filterd = parkSpaceList.value.filter(
            (item: any) => item.parkId === val
        )
        const options = filterd.map((item: any) => {
            return {
                id: item.id,
                name: item.number,
            }
        })
        parkSpaceOptions.value = options
    }
)

// 获取套餐列表
const packageList = ref<any>([])
const getPackageList = async () => {
    const res = (await getPackagePageApi({
        limit: 1000,
    })) as any
    packageList.value = res.rows
    form.value.packageId = res.rows[0].id
}
const getPackageById = (id: number) => {
    return packageList.value.find((item: any) => item.id === id)
}

// 支付方式列表
const payMethodList = ref<any>([])
const getPayMethodList = async () => {
    const res = (await getPayMethodPageApi({
        limit: 1000,
    })) as any
    payMethodList.value = res.rows
}

getParkOptions()
getParkSpaceList()
getPackageList()
getPayMethodList()
</script>

<style scoped></style>
